//
//  HiAliyunOSSManager.swift
//  HiYue
//
//  Created by 嗨约网信 on 2017/7/5.
//  Copyright © 2017年 嗨约网信. All rights reserved.
//

import UIKit

var aliyunClient = OSSClient()//创建OSS服务的ios客户端

//let endPoint     = "http://oss-cn-shenzhen.aliyuncs.com"  //OSS服务的endPoint
//let baseIamgUrl  = "http://bigmiaomiao.oss-cn-shenzhen.aliyuncs.com/" //需要传给服务器的基础URL
//let bucketName   = "bigmiaomiao" //

let endPoint     = "http://static.hiyueke.cn"  //OSS服务的endPoint
let baseIamgUrl  = "http://static.hiyueke.cn/" //需要传给服务器的基础URL
let file         = "image/201709/" //文件夹
let bucketName   = "hiyue-oss-dev" //

class HiAliyunOSSManager: NSObject {
    
    typealias SingleImageSuccessCallBack    = (_ urlString : String) ->()//单个图片上传的成功返回
    typealias MoreImageSuccessCallback  = (_ urlStringArray : [String]) ->() //多个图片上传的成功返回
    typealias FailureCallBack = ()->() //请求失败的返回
    
    var accessKeyId = "LTAIoQtRWqShavde"
    var secretKeyId = "FKACZDtrnqoyQYDPcfSUIsHCAbDAwY"
    var securityToken = ""
    
    //单例
    static let shareInstance : HiAliyunOSSManager = HiAliyunOSSManager()
    
    //初始化OSS服务的ios客户端
    func initOSSclient() {
        //通过获得的token来加签加签器
//        let credential = OSSStsTokenCredentialProvider(accessKeyId: accessKeyId, secretKeyId: secretKeyId, securityToken: securityToken)
//        if let credential = credential {
//            aliyunClient = OSSClient(endpoint: endPoint, credentialProvider: credential)
//            
//            aliyunClient.credentialProvider = OSSFederationCredentialProvider(federationTokenGetter: { () -> OSSFederationToken? in
//                //自动更新token
//                let tcs = OSSTaskCompletionSource<AnyObject>.init()
//                
//                HttpManager.requestHeaderData(.Get, urlString: "", finishedCallBack: { (response) in
//                    tcs.setResult(response as AnyObject)
//                }, failedCallBack: { (failedrror) in
//                    
//                    if let error = failedrror {
//                        tcs.setError(error)
//                    }
//                    
//                })
//                
//                tcs.task.waitUntilFinished()
//                
//                //如果tcs.task.error 不存在 就说明有加签结果
//                guard  tcs.task.error == nil  else{
//                    return nil
//                }
//                
//                guard let response = tcs.task.result as? JSON else{
//                    return nil
//                }
//                
//                let token = OSSFederationToken()
//                token.tAccessKey = response["accessKeyId"].stringValue
//                token.tSecretKey = response["accessKeySecret"].stringValue
//                token.tToken     = response["token"].stringValue
//                token.expirationTimeInGMTFormat = response["expiration"].stringValue //指明token的实效时间
//                return token
//                
//            })
//        }
        
        //TODO : 测试
        let credential = OSSPlainTextAKSKPairCredentialProvider(plainTextAccessKey: accessKeyId, secretKey: secretKeyId)
        aliyunClient   = OSSClient(endpoint: endPoint, credentialProvider: credential!)
        
        
        
    }
    /// 异步上传单张图片包括普通图片到阿里云OSS，请调用此方法
    ///
    /// - Parameters:
    ///   - image: 图片
    ///   - imageType: 图片类型(普通图片或用户头像)
    ///   - successCallback: 成功回调(urlString为图片在阿里云OSS上的存储地址)
    ///   - failureCallback: 失败回调
    func uploadImageAsync(withImage image : UIImage,
                          successCallback : @escaping SingleImageSuccessCallBack,
                          failureCallback : @escaping FailureCallBack)  {
        //globallyUniqueString 唯一标示符,每次调用都会不一样
        let fileName = "\(ProcessInfo.processInfo.globallyUniqueString).jpg"
        
        let put = setOSSPutObject(withImage: image, coefficientNum: 0.6 ,fileName: fileName)
        let putTask = aliyunClient.putObject(put)
        putTask.continue({ (task) -> Any? in
            if task.error == nil {
                successCallback("\(baseIamgUrl)\(file)\(fileName)")
            } else {
                print(task.error!)
                failureCallback()
            }
            return nil
        })
        
    }
    
    /// 同步上传单张图片包括普通图片到阿里云OSS，请调用此方法
    ///
    /// - Parameters:
    ///   - image: 图片
    ///   - imageType: 图片类型(普通图片或用户头像)
    ///   - successCallback: 成功回调(urlString为图片在阿里云OSS上的存储地址)
    ///   - failureCallback: 失败回调
    func uploadImageSync(withImage image : UIImage,
                         successCallback : @escaping SingleImageSuccessCallBack,
                         failureCallback : @escaping FailureCallBack) {
        //globallyUniqueString 唯一标示符,每次调用都会不一样
        let fileName = "\(ProcessInfo.processInfo.globallyUniqueString).jpg"
        
        let put = setOSSPutObject(withImage: image, coefficientNum: 0.6, fileName: fileName)
        
        let putTask = aliyunClient.putObject(put)
        putTask.waitUntilFinished()
        
        if putTask.error == nil {
            successCallback("\(baseIamgUrl)\(file)\(fileName)")
        }else {
            failureCallback()
        }
     
    }
    
    /// 上传多个图片(只包括普通图片)到阿里云OSS，请调用此方法
    ///
    /// - Parameters:
    ///   - images: 图片数组
    ///   - successCallback: 成功回调(urlStringArray为图片在阿里云OSS上的存储地址数组)
    ///   - failureCallback: 失败回调
    func uploadImagesAsyns(withImages images: [UIImage],
                           moresuccessCallback: @escaping MoreImageSuccessCallback,
                           failureCallback: @escaping FailureCallBack) {
        DispatchQueue.global().async {
            var urlStringArray = [String]()
            for image in images {
                DispatchQueue.global().sync {
                    self.uploadImageSync(withImage: image, successCallback: { (imageURLString) in
                        urlStringArray.append(imageURLString)
                        if urlStringArray.count == images.count {
                            DispatchQueue.main.async {
                                moresuccessCallback(urlStringArray)
                            }
                        }
                        
                    }, failureCallback: {
                        DispatchQueue.main.async {
                            failureCallback()
                        }
                    })
                }
            }
        }
    }
    
    /// 上传图片到阿里云OSS，设置OSSPutObjectRequest
    ///
    /// - Parameters:
    ///   - image: 图片
    ///   - coefficientNum: 图片的压缩系数
    ///   - fileName: 图片所拥有的名字
    func setOSSPutObject(withImage : UIImage ,coefficientNum : CGFloat , fileName : String) -> OSSPutObjectRequest {
        
        let objectKey = "\(file)\(fileName)"
        let imageData = UIImageJPEGRepresentation(withImage, coefficientNum)
        let filePath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)
        try! imageData?.write(to: filePath)
        
        let put = OSSPutObjectRequest()
        
        put.bucketName = bucketName
        put.objectKey = objectKey //这个路径是真的url路径
        put.uploadingFileURL = filePath
        
        return put
    }
    
}
